<?php

namespace app\common\model;

use think\Model;

/**
 * 新闻栏目model
 */
class NewsCate extends Model
{
    /**
     *获取栏目类型
     * */
    public static function get_cate_type($id)
    {
        return self::where(['id' => $id])->value('cate_type');
    }

    /**
     * 栏目cate_path关系
     * */
    public static function set_cate_path($id)
    {
        return static::get_cate_pid($id, $id);
    }

    public static function get_cate_pid($id, $cate_path = '')
    {
        $cate_pid = self::where(['id' => $id])->value('cate_pid');
        if ($cate_pid != 0) {
            return static::get_cate_pid($cate_pid, $cate_pid . '-' . $cate_path);
        }
        return $cate_path;
    }

    /**
     * 后台栏目树
     * */
    public static function cate_tree_console()
    {
        $all_cate = self::field('id,cate_name,cate_type,cate_pid,is_show,sort')->order('is_show desc,sort asc,id asc')->select();
        $cate_tree = static::set_cate_tree_console($all_cate);
        return $cate_tree;

    }

    public static function set_cate_tree_console($all_cate, $cate_pid = 0, $cate_lev = 1)
    {
        static $cate_tree = [];
        foreach ($all_cate as $k => $v) {
            if ($v['cate_pid'] == $cate_pid) {
                $all_cate[$k]['cate_lev'] = $cate_lev;
                $cate_tree[] = $all_cate[$k];
                static::set_cate_tree_console($all_cate, $v['id'], $cate_lev + 1);
            }

        }

        return $cate_tree;
    }

    /**
     * 前台栏目
     * */
    public static function cate_tree_home()
    {
        $all_cate = self::where(['is_show' => 1, 'cate_pid' => 0])->field('id,cate_name,cate_type,gourl')->order('sort asc')->select();
        $cate_tree = static::set_cate_tree_home($all_cate);
        return $cate_tree;
    }

    public static function set_cate_tree_home($all_cate)
    {
        foreach ($all_cate as $k => $v) {
            $son = self::where(['is_show' => 1, 'cate_pid' => $v['id']])->field('id,cate_name,cate_type,gourl')->order('sort asc')->select();

            $all_cate[$k]['son'] = $son ? $son : [];
        }
        return $all_cate;
    }

    /**
     * 前台查询是否有子栏目
     * */
    public static function has_son_cate($id)
    {
        return self::where(['is_show' => 1, 'cate_pid' => $id])->order('sort asc')->select();
    }

    /**
     *前台 返回cate_path_arr数组  继而获得主栏目和当前位置信息
     * */
    public static function cate_path_arr($id)
    {
        $cate_path = self::where(['id' => $id])->value('cate_path');
        $cate_path_arr = explode('-', $cate_path);
        return $cate_path_arr;
    }

    /**
     *前台 返回同级栏目
     * */
    public static function label_arr($cate_pid)
    {
        return self::where(['cate_pid' => $cate_pid, 'is_show' => 1])->field('id,cate_name')->order('sort asc')->select();
    }

    /**
     * 前台 返回详细模板 b_tpl
     * */
    public static function cate_b_tpl($id)
    {
        return self::where(['id' => $id])->value('b_tpl');
    }

}
